package com.scalar.chiptrack.adaptor.ikanos.tower;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import HTTPClient.Cookie;
import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * User: ChandraSekhar
 * Date: Jul 10, 2008
 * Time: 1:12:10 PM
 */
public class TowerAdaptor extends JobHandler implements AdaptorConstants
{
    private static String HOST = "etower.towersemi.com";
    private static int PORT = 80;

    //Login URI
    private static String FORM_LOGIN_ACTION   = "/irj/servlet/prt/portal/prtroot/com.sap.portal.navigation.portallauncher.default";
    //Logistics URI
    private static String LOGISTICS_ACTION    = "/irj/go/km/docs/documents/HTML/HTML%20forms/logistics.htm";
    //WIP URI's
    private static String  WIP_REPORT_ACTION  = "/irj/servlet/prt/portal/prtpos/pcd!253aportal!255fcontent!252fcom!252etsl!252eeTower!252fcom!252etsl!252eRoles!252fcom!252etsl!252eetower!252eLogistic!255fInformation!252fcom!252etsl!252elogistic!252fcom!252etsl!252ewipReports!7bpreview!7d.com!252etsl!252eWipReport!7bpreview!7d_layoutComponent!7bpreview!7d-/prttarget/com!252etsl!252eWipReport/prteventname/HtmlbEvent/prtroot/pcd!3aportal_content!2fcom.tsl.eTower!2fcom.tsl.Roles!2fcom.tsl.etower.Logistic_Information!2fcom.tsl.logistic!2fcom.tsl.wipReports";
    //Ship report URI's
    private static String SHIP_RPT_ACTION     = "/irj/servlet/prt/portal/prtpos/pcd!253aportal!255fcontent!252fcom!252etsl!252eeTower!252fcom!252etsl!252eRoles!252fcom!252etsl!252eetower!252eLogistic!255fInformation!252fcom!252etsl!252elogistic!252fcom!252etsl!252eshipments!7bpreview!7d.com!252etsl!252eShipmentReport!7bpreview!7d_layoutComponent!7bpreview!7d-/prttarget/com!252etsl!252eShipmentReport/prteventname/HtmlbEvent/prtroot/pcd!3aportal_content!2fcom.tsl.eTower!2fcom.tsl.Roles!2fcom.tsl.etower.Logistic_Information!2fcom.tsl.logistic!2fcom.tsl.shipments";
    //DownLoad Actions
    private static String DOWNLOAD_ACTION     = "/irj/servlet/prt/portal/prtroot/TowerUserManagementDoron.ReportFileCreator";
    //Logout URI
    private static String FORM_LOGOUT_ACTION  = "/irj/portal?logout_submit=1";

    public static String FILE_NAME_WIP_STATUS   = "Tower_WIP_Report";
    public static String FILE_NAME_SHIP_STATUS  = "Tower_Shipment_Report";

    public static final String ADAPTOR_NAME     = "Tower_WIP";

    private Logger m_adaptorLogger  = null;
    private String m_dataOutputDir  = null;//"c:/chiptrac_ikanos/adaptor_out/tower/";
    private String m_username       = null;//"carloss";
    private String m_password       = null;
    private int    m_adaptor_id     = -1;

    public TowerAdaptor() throws ScalarException
    {
        try
        {
           VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_TOWER, LOCATION_TYPE_FAB);

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger  =  AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_TOWER );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( ScalarException se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading TOWER Adaptor Username, Password details from database, Exception: " + se );
            throw se;
        }
    }

    public static void main( String[] args )  throws Exception
    {
        try
        {
            new TowerAdaptor().execute();
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
    }

    public void execute() throws Exception
    {

        m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
        
        //Print the header details
        AdaptorUtils.printHeader(VENDOR_NAME_TOWER, CONSTANT_ADAPTOR);

        AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

        try
        {
            //login to the Site
            HTTPConnection conn = login( HOST, PORT, m_username, m_password );

            if ( conn != null )
            {
                BufferedReader reader = null;

               //Request for wip status
                HTTPResponse rsp = requestWipReport( conn );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the Wip Report..." );
                        log( "\n\tDownloading and saving the Wip Report..." );
                        AdaptorUtils.saveAsFile( reader , m_dataOutputDir, FILE_NAME_WIP_STATUS ,FILE_EXTN_CSV);

                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Wip Report from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip Report" );
                    throw new ScalarException( "Could not create response object of  Wip Report" );
                }

                //Request for Shipment Report
                rsp = requestShipmentReport( conn );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\t\tDownloading and saving the Shipment Report..." );
                        log( "\tDownloading and saving the Shipment Report..." );
                        AdaptorUtils.saveAsFile ( reader , m_dataOutputDir, FILE_NAME_SHIP_STATUS , FILE_EXTN_CSV);

                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SHIP_STATUS, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Shipment Report from Buffer Reader" );
                        throw new ScalarException( "Could not save Shipment Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Shipment Report" );
                    throw new ScalarException( "Could not create response object of Shipment Report" );
                }

                //logout from the site
                logout( conn );

                if ( reader != null )
                {
                    reader.close();
                    reader = null;
                }
            }
            else
            {
                log( "Could not able to get the Connection to Tower web site" );
                throw new ScalarException( "Could not able to get the Connection to Tower web site" );
            }
        }
        catch (Exception e )
        {
            System.out.println("ERROR!! ERROR!! ERROR!! Exception while running Tower Adaptor");
            e.printStackTrace();
            throw e;
        }
    }

    private HTTPConnection login( String host, int port, String userId, String password ) throws Exception
    {
        HTTPConnection conn = null;
        byte[] data         = new byte[1024];
        
        conn = new HTTPConnection( host, port );

        NVPair defaultHeaders[] = new NVPair[7];
        defaultHeaders[0] = new NVPair( "Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*" );
        defaultHeaders[1] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[2] = new NVPair( "UA-CPU", "x86" );
        defaultHeaders[3] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.2)" );
        defaultHeaders[4] = new NVPair( "Host", host );
        defaultHeaders[5] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[6] = new NVPair( "Set-Cookie", "");
        // Accept all cookies
        CookieModule.setCookiePolicyHandler( null );
        CookieModule.discardAllCookies();
        conn.addDefaultModule( CookieModule.class, -1 );
        conn.setDefaultHeaders( defaultHeaders );

        Cookie[] cookie1 = CookieModule.listAllCookies();
        
        System.out.println("cookie1.length = " + cookie1.length);
        for ( int i = 0; i < cookie1.length; i++ )
        {
            System.out.println("i="+i+" Name = "+cookie1[i].getName()+" Value = "+cookie1[i].getValue());
            CookieModule.removeCookie(cookie1[i]);
        }

        
        System.out.print( "Trying to login...." );
        log( "\nTrying to log in... " );

        HTTPResponse rsp = conn.Get( "/irj/portal" );

        NVPair[] formData = new NVPair[6];

        formData[0] = new NVPair( "login_submit", "on" );
        formData[1] = new NVPair( "login_do_redirect", "0" );
        formData[2] = new NVPair( "no_cert_storing", "on" );
        formData[3] = new NVPair( "j_user", userId );
        formData[4] = new NVPair( "j_password", password );
        formData[5] = new NVPair( "j_authscheme", "default" );

        rsp = conn.Post( FORM_LOGIN_ACTION , formData );
        
        while (rsp.getInputStream().read(data) != -1) {
                    log(new String(data));
                }


        //readData( rsp, 0 );

        rsp = conn.Get(LOGISTICS_ACTION);

        //readData( rsp, 0 );
        System.out.print( "done." );
        log( "done" );
        return conn;
    }
   /**
    *  To Log out from the Tower web site
    * @param conn
    * @throws Exception
    */
    private void logout( HTTPConnection conn ) throws Exception
    {
        System.out.println( "Submitting Request for logout......" );

        log( "\nSubmitting Request for logout...." );

        HTTPResponse rsp = conn.Get( FORM_LOGOUT_ACTION );
        readData( rsp, 1 );

        System.out.print( "done" );
        log( "done." );
    }
     /**
      * To get the Tower Wip details sheet
      * @param conn  HttpConnection
      * @return HTTPRespone
      * @throws Exception  all exceptions
      */
    private HTTPResponse requestWipReport( HTTPConnection conn ) throws Exception
    {
        System.out.println( "\nSubmitting request for Wip Report....." );
        HTTPResponse rsp = conn.Get( WIP_REPORT_ACTION );
        //readData( rsp,1 );

        rsp = conn.Get( DOWNLOAD_ACTION );
        //readData( rsp,0 );
        return rsp;
    }

    public HTTPResponse requestShipmentReport( HTTPConnection conn ) throws Exception
    {
        System.out.println( "Submitting request for Ship Report....." );
        
        HTTPResponse rsp = conn.Get( SHIP_RPT_ACTION );
        //readData( rsp, 1 );

        rsp = conn.Get( DOWNLOAD_ACTION);
        //readData( rsp, 0 );

        return rsp;
    }

    public void readData( HTTPResponse rsp, int debug ) throws Exception
    {
        BufferedReader reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );

        String line = null;
        while ( ( line = reader.readLine() ) != null )
        {
            if ( debug == 0 )
            {
                //System.out.println(line);
                log(line);
            }
         }
        
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            if ( debug == 0 )
            {
                //System.out.println( new String( data ) );
                log( new String( data ) );
            }

        }*/
    }

    private void log( String message )
    {

        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
